//
//  VCWebView.swift
//  ztConference
//
//  Created by HippieFox on 2019/8/7.
//  Copyright © 2019 HPFx. All rights reserved.
//

import UIKit
import WebKit
import JavaScriptCore


///屏幕宽度
let FXScreenWidth = UIScreen.main.bounds.size.width

///屏幕高度
let FXScreenHeight = UIScreen.main.bounds.size.height
let isIphoneX = FXScreenHeight >= 812 ? true : false
let navigationBarHeight : CGFloat = isIphoneX ? 88 : 64


class VCWebView: UIViewController {
    static let NOTIFICATION_REGISTER_SUCCESS = Notification.Name.init("NOTIFICATION_REGISTER_SUCCESS")
    static let NOTIFICATION_FILLINFO_SUCCESS = Notification.Name.init("NOTIFICATION_FILLINFO_SUCCESS")

    
    @objc var urlStr:String?
    
//     @objc let context: JSContext = JSContext()

    
      @objc lazy  var webView:WKWebView = {
        let size = UIScreen.main.bounds.size
        
        let frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height - navigationBarHeight)
        let config = WKWebViewConfiguration.init()
        
        let userContent = WKUserContentController()
        userContent.add(self, name: "CallMainPage")

        config.userContentController = userContent

        
        let wv =  WKWebView.init(frame: frame, configuration: config)
        wv.navigationDelegate = self
        wv.uiDelegate = self

        return wv
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        self.view.addSubview(self.webView)
        
        
        if let urlS = self.urlStr{
            
            if let url = URL.init(string: urlS){
                
                self.webView.load(URLRequest.init(url: url))
            }
        }
        
        
        
       let gb = UIBarButtonItem.init(image: UIImage.init(named: "guanbi"), style: .plain, target: self, action: #selector(guanbi))
        
        let close = UIBarButtonItem.init(image: UIImage.init(named: "左箭头"), style: .plain, target: self, action: #selector(back))
        
        self.navigationItem.leftBarButtonItems = [close, gb]
        
    }
    
    
    @objc private func guanbi(){
        self.navigationController?.popViewController(animated: true)

    }
    
    @objc private func back(){
        if self.webView.canGoBack == true{
            self.webView.goBack()
        }
    }


}

extension VCWebView:WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate{
   @objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.name)
        
        if message.name == "CallMainPage"{//注册完成了
          self.navigationController?.popViewController(animated: true)
        }
        
            
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.title = webView.title
    }
    
    
 
}
